package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品
     */
    @Override
    @Transactional
    public void insert(DishDTO dishDTO) {
        //1.创建菜品对象（复用性）
        Dish dish = new Dish();
        //2.赋值
        BeanUtils.copyProperties(dishDTO, dish);
        //3.调用菜品Mapper接口执行SQL
        dishMapper.insert(dish);
        //4.获取口味对象（口味对象所需值，都在dishDTO里，封装了口味对象）
        List<DishFlavor> flavorList = dishDTO.getFlavors();
        //5.判断口味是否为空，以免空指针异常
        if (flavorList.size() > 0 && flavorList != null) {
            //5.1.给口味对象写入逻辑外键，也及时绑定菜品的id
            flavorList.forEach(f -> f.setDishId(dish.getId()));
            //6.调用口味的Mapper接口执行SQL
            dishFlavorMapper.insert(flavorList);
        }
    }

    /**
     * 分页查询菜品加模糊查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult select(DishPageQueryDTO dishPageQueryDTO) {
        //1.开启分页
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        //2.调用Mapper查询全部
        List<DishVO> dishVOList = dishMapper.select(dishPageQueryDTO);
        //3.封装page（DishVO）
        Page<DishVO> pageVO = (Page<DishVO>) dishVOList;
        //4.返回集合对象
        return new PageResult(pageVO.getTotal(), pageVO.getResult());
    }

    /**
     * 根据ids删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional
    public void delete(List<Long> ids) {
        //1.起售状态的菜品不能删除，所以获取所有id的状态（1|2），数据层只负责查数据，无业务
        List<Integer> idStatus = dishMapper.selectById(ids);
        //2判断是否是起售
        idStatus.forEach(is -> {
            if (is == StatusConstant.ENABLE)
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        });
        //3.被套餐关联的菜品也不能删除
        /*
            可以根据菜品id查找有无套餐，去一个返回值就行，不用*
            可以套餐id，但就用菜品id
         */
        List<Long> idDish = setmealDishMapper.selectById(ids);
        //4.判断是否有值
        if (idDish.size() > 0 && idDish != null)
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        //5.删除菜品
        dishMapper.delete(ids);
        //6.关联的口味也要删除
        dishFlavorMapper.delete(ids);
    }

    /**
     * 根据id查询菜品表
     */
    @Override
    public DishVO selectById(Long id) {
        //1.创建一个返回的DishVO对象来准备接值
        DishVO dishVO = new DishVO();
        //2.根据id查询出对应菜品
        Dish dish = dishMapper.getById(id);
        //3.将菜品赋值给DishVO
        BeanUtils.copyProperties(dish, dishVO);
        //4.根据id查询出对应口味（一个id多个口味，十个集合）
        List<DishFlavor> dishFlavorList = dishFlavorMapper.getById(id);
        //5.口味赋值给DiskVO，口味为DishVo里封装的一个List值
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    /**
     * 修改菜品信息，包含口味
     *
     * @param dishVO
     */
    @Override
    public void update(DishVO dishVO) {
        //1.创建Dish对象
        Dish dish = new Dish();
        //2.给对象赋值
        BeanUtils.copyProperties(dishVO, dish);
        //3.调用dishMapper执行update语句，并返回主键，让下面创建的口味绑定菜品
        dishMapper.update(dish);
        //4.创建口味对象
        DishFlavor dishFlavor = new DishFlavor();
        //5.根据dish_id删除指定id所有口味
        dishFlavorMapper.deleteByDishId(dish.getId());
        //6.判断dishVO的口味是否为空
        List<DishFlavor> flavorList = dishVO.getFlavors();
        //7.不为空就绑定菜品id
        if (flavorList != null && flavorList.size() > 0) {
            flavorList.forEach(fla -> fla.setDishId(dish.getId()));
            //8.调用口味Mapper执行insert语句，并指定dish_id的值
            dishFlavorMapper.insert(flavorList);
        }
        //SetmealDish有一个菜品名字的冗余字段，这里修改了名字，对应的冗余字段也要改
        SetmealDish setmealDish = SetmealDish.builder()
                .dishId(dishVO.getId())
                .name(dishVO.getName())
                .price(dishVO.getPrice())
                .build();
        setmealDishMapper.update(setmealDish);
    }

    /**
     * 根绝分类id查询菜品
     */
    @Override
    public List<Dish> getByTypeId(Long id) {
        Dish dish = Dish.builder()
                .categoryId(id)
                .status(StatusConstant.ENABLE)
                .build();
        List<Dish> dishList = dishMapper.list(dish);
        return dishList;
    }

    /**
     * 条件查询菜品和口味
     *
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 修改菜品状态
     */
    @Override
    public void updateStatus(Integer status, Long id) {
        //判断是否将状态设置为禁用（菜品禁用，关联的套餐也要禁用）
        if (status == StatusConstant.DISABLE){
            //查询菜品关联了哪些套餐
            List<Long> setmealIds = setmealDishMapper.getSetmealIdByDishId(id);
            //判断如果有
            if (setmealIds != null || setmealIds.size() != 0)
                //将套餐设为停用（套餐里有未启用菜品套餐是无法启售的）
               setmealMapper.setStatus(setmealIds,status);
        }
        dishMapper.updateStatus(status, id);
    }
}
